package com.wxxymaker.utils.auth;

import com.blade.kit.Base64;
import com.blade.kit.EncrypKit;
import com.wxxymaker.utils.auth.AuthModel;

/**
 * @Author: Soft
 * @Date: 2018/5/7 17:35
 * @Desc: 需要验证的对象与字符串转化，用于安全的保存到cookie session中
 */
public class AuthUtil {
    public final static String Spacing = "_";
    /**
     * 将用户的账号密码进行加密处理，以便保存在cookie或session中
     * @param user 带有账号密码的用户实体
     * @return 转化后的字符串
     */
    public static String toBase64Md5(AuthModel user) {
        if (null != user && null != user.getUsername() && null != user.getPassword()) {
            String base64Name = Base64.encodeToString(user.getUsername().getBytes(), Base64.NO_PADDING).replace("\n", "");
            String md5Pass    = EncrypKit.md5(user.getPassword());
            return base64Name + Spacing + md5Pass;
        }
        return null;
    }

    /**
     * 将经过处理的字符串转化为user对象
     * @param s 处理过的字符串
     * @return user
     */
    public static AuthModel fromString(String s, Class<? extends AuthModel> clazz) {
        AuthModel model = null;
        try {
            model = clazz.newInstance();
            if (null != s) {
                String[] strings = s.split(Spacing);
                if (strings.length == 2) {
                    model.setUsername(new String(Base64.decode(strings[0], Base64.NO_PADDING)));
                    model.setPassword(strings[1]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }
}
